const config = require('./config');
var cors = require('cors');// 引入cors插件

const express = require('express'); // 引入express框架
const app = express();


const passport = require("passport"); //引入passport插件
app.use(passport.initialize()); //passport初始化

require("./config/passport")(passport);


const apiUsers = require("./sources/api/users"); //引入api users.js

// const autoIncrement = require('mongoose-auto-increment');

/**
 * Express框架默认使用body-parser作为请求体解析中间件
 * 处理application/json、application/x-www-form-urlencoded两种格式的请求
 * 所有路由处理器的req.body中访问请求参数
 */
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

//使用中间件实现跨域请求
app.use(cors());//
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*"); //允许的来源
    res.header("Access-Control-Allow-Headers", "Content-Type"); //请求的头部
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); //允许请求的方法
    next();
})


// 引入路由
app.use(config.apiPath + '/', apiUsers);

// 启动项目监听端口
app.listen(config.port);


/**
 * mongodb数据连接
 */
const mongoose = require("mongoose");
//useNewUrlParser: true添加参数：current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect
mongoose.connect(config.db, {
        useNewUrlParser: true
    })
    .then(() => console.log("数据库连接建立。")) //promise用法
    .catch(err => console.log(err));


//引入log4js log日志
const log = require("./sources/logger");
log.use(app);